const api = require('../../utils/api')
const util = require('../../utils/util')
const layer = require('../../utils/layer')
const listTouchBehavior = require('../../utils/listTouchBehavior')
const app = getApp()
Component({
    // 混入列表左移
    behaviors: [listTouchBehavior],
    /**
     * 页面的初始数据
     */
    data: {
        myTop: app.globalData.CustomBar, // 顶部工具栏距离手机顶部的距离
        editModelShow: false,
        billId: undefined,
        pamram: {
            year: 1,
            month: 1,
            teamId: 0,
        },
        page: {
            current: 1,
            size: 15,
            records: [],
            total: 0,
            length: 0,// 数据长度
        },
        isEnd: false, // 是否到底
        dateMultiIndex: [0, 0],
        dateMultiArray: [],
        expenditure: ['0', '00'], // 支出  数组存整数部分和小数部分
        income: ['0', '00'], // 收入
        teamPicker: {
            range: [{ title: "不选择", value: '0' }],
            index: 0,
        },
        teamId: 0,
    },
    /**
     * 初始化页面时触发
     */
    attached() {
        // 初始化时间选择器列表参数
        layer.showLoading("数据获取中...")
        let date = new Date();
        let dateMultiArray = [[], []];
        let dateMultiIndex = [];
        let param = this.data.pamram;
        param.year = date.getFullYear();
        param.month = date.getMonth() + 1;
        /// 年份从1998年至今 
        for (let i = 1998, index = 0; i <= date.getFullYear(); i++, index++) {
            dateMultiArray[0][index] = i + '年';
            // 设置默认选中今年
            if (i == date.getFullYear()) {
                dateMultiIndex[0] = index;
            }
        }
        /// 月份 12个月
        for (let i = 1; i <= 12; i++) {
            dateMultiArray[1][i - 1] = i + '月';
            // 设置默认选中今月 月份从0计数，下标也从0计数，这里刚好抵消
            if (i == date.getMonth() + 1) {
                dateMultiIndex[1] = i - 1;
            }
        }
        // 初始化团队picker
        api.post("/team/list", { userId: wx.getStorageSync("userId") }).then(res => {
            wx.hideLoading();
            let teamPicker = this.data.teamPicker;
            if (res.data && res.data.length > 0) {
                teamPicker.range = teamPicker.range.concat(res.data.map(item => {
                    return {
                        title: item.name,
                        value: item.id
                    };
                }))
            }
            this.setData({
                dateMultiArray,
                dateMultiIndex,
                param,
                teamPicker
            })
            // 获取一次数据
            this.getPage();
        });
    },
    methods: {
        /**
         * 查看详情
         */
        detail(e) {
            let id = e.target.dataset.id;
            if (!id || id === 'undefined') {
                return;
            }
            this.setData({
                billId: id + '',
                editModelShow: true
            })
        },
        // 创建一个新的账单
        createBill() {
            this.setData({
                billId: '',
                editModelShow: true
            })
        },
        /**
         * 清除分页，重新查询数据
         */
        reGetPage() {
            this.setData({
                page: {
                    current: 1,
                    size: 15,
                    records: [],
                    total: 0,
                    length: 0,// 数据长度
                },
            })
            this.getPage();
        },
        /**
         * 获取分页数据
         */
        getPage() {
            let that = this
            console.log("获取数据");
            let param = this.data.param
            let page = this.data.page
            api.post("/bill/page", {
                page: {
                    size: page.size,
                    current: page.current,
                },
                param: param

            }).then(res => {
                // 处理收支
                // 如果不是第一页就进行数据拼接
                if (that.data.page.current != 1) {
                    res.data.records = that.data.page.records.concat(res.data.records); // 往原分页记录后面追加查询的记录
                    res.data.length = that.data.page.length + res.data.length; // 往原分页记录后面追加查询的记录
                }
                page = res.data;
                this.setData({
                    page,
                    income: this.getFloatArr(res.data.income),
                    expenditure: this.getFloatArr(res.data.expenditure),
                    isEnd: this.calcIsEnd(page)

                })
            });
        },
        /**
        * 
        * @returns 判断是否到底了
        */
        calcIsEnd(page) {
            if (page.length >= Number.parseInt(page.total)) {
                return true;
            }
            return false;
        },
        /**
         * 滑动触底事件
         */
        bindscrolltolower() { // 滑动触底事件
            let page = this.data.page
            if (page.total > page.records.length) {
                // 刷新更多内容，增加size
                page.current++; // 翻页
                this.setData({
                    page
                })
                // 发送刷新请求
                this.getPage()
            }
        },
        // pickerDate修改
        dateChange(e) {
            let dateMultiIndex = e.detail.value
            let param = this.data.pamram;
            let dateMultiArray = this.data.dateMultiArray;
            // 设置查询参数的年月
            param.year = getValueNotEnd(dateMultiArray[0][dateMultiIndex[0]]);
            param.month = getValueNotEnd(dateMultiArray[1][dateMultiIndex[1]]);
            this.setData({
                dateMultiIndex,
                param
            })
        },
        // pickerTeam修改
        teamChange(e) {
            let teamPicker = this.data.teamPicker
            let param = this.data.pamram
            teamPicker.index = e.detail.value
            param.teamId = teamPicker.range[teamPicker.index].value
            this.setData({
                teamPicker,
                param,
                teamId: param.teamId
            })
            // 重新获取账单数据
            this.reGetPage();
        },
        // 获取数字 的整数小数数组
        getFloatArr(number) {
            // 先转字符串后按.分割
            let numberArr = (number + "").split(".");
            if (numberArr.length == 1) {
                numberArr[1] = '00';
            }
            return numberArr;
        },
        // 列改变
        dateColumnChange(e) {
            // 暂不处理
        },
        // 获取去掉末尾的值
        getValueNotEnd(value) {
            return value.substring(0, value.length - 1);
        },
        // 删除账单
        deleteBill(e) {
            let id = e.currentTarget.dataset.id;
            let that = this;
            layer.showModal(() => {
                wx.showLoading();
                api.get("/bill/delete/one", { id: id }).then(res => {
                    layer.showToast(res.message);
                    setTimeout(() => {
                        that.reGetPage();
                    }, 500);
                });
            }, '提示', `确定要删除该账单吗？`);
        },
    }
})